package edu.sdwu.liqing.qasystem.aspect;

import edu.sdwu.liqing.qasystem.annotation.HasRole;
import edu.sdwu.liqing.qasystem.entity.QaUser;
import edu.sdwu.liqing.qasystem.model.Response;
import edu.sdwu.liqing.qasystem.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.SuppressAjWarnings;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Objects;

@Aspect
@Order(2)
@Component
@Slf4j
@SuppressAjWarnings
public class RoleAspect {

    @Autowired
    RequestUtil requestUtil;

    @Pointcut("@annotation(hasRole)")
    public void pointCut(HasRole hasRole) {}

    //做权限校验
    @Around("pointCut(hasRole)")
    public Object doCheckLogin(ProceedingJoinPoint point, HasRole hasRole) throws Throwable {
        //首先获取当前用户
        QaUser user = requestUtil.getCurrentUser();
        //遍历hasRole的参数 判断是否存在
        for (String s : hasRole.value()) {
            if (StringUtils.equalsIgnoreCase(s, user.getRoleName())) {
                //存在角色 就放行
                return point.proceed();
            }
        }
        //如果不存在权限 就打出日志，并且拦截
        log.info("无权访问");
        return Response.create(403, "无权访问", null);
    }

}
